<template>
  <div class="main">
    <a-form id="formLogin" class="user-layout-login" ref="formLogin" :form="form" @submit="handleSubmit">
      <!-- <a-tabs
        :activeKey="customActiveKey"
        :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
        @change="handleTabClick"
      > -->
      <!-- <a-tab-pane key="tab1" tab="账号密码登录"> -->
      <p class="login-title">账号密码登录</p>
      <a-alert v-if="isLoginError" type="error" showIcon style="margin-bottom: 24px" :message="errorMsg" />
      <a-form-item>
        <a-input
          size="large"
          type="text"
          placeholder="机构编码"
          v-decorator="['orgCode', { rules: [{ required: true, message: '请输入机构编码' }], validateTrigger: 'blur' }]"
        >
          <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-input
          size="large"
          type="text"
          placeholder="请输入帐号"
          v-decorator="[
            'loginText',
            {
              initialValue: '',
              rules: [{ required: true, message: '请输入帐户名' }, { validator: handleLoginTextOrEmail }],
              validateTrigger: 'change'
            }
          ]"
        >
          <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
        </a-input>
      </a-form-item>

      <a-form-item>
        <a-input
          size="large"
          type="password"
          autocomplete="false"
          placeholder="请输入密码"
          v-decorator="[
            'password',
            { initialValue: '', rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur' }
          ]"
        >
          <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
        </a-input>
      </a-form-item>

      <a-row :gutter="16">
        <a-col class="gutter-row" :span="16">
          <a-form-item>
            <a-input
              size="large"
              type="text"
              placeholder="验证码"
              v-decorator="[
                'captcha',
                { rules: [{ required: true, message: '请输入验证码' }], validateTrigger: 'blur' }
              ]"
            >
              <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <img class="getCaptcha" :src="codesrc" @click="getImgCode" />
        </a-col>
      </a-row>
      <!-- </a-tab-pane> -->
      <!-- <a-tab-pane key="tab2" tab="手机号登录">
          <a-form-item>
            <a-input size="large" type="text" placeholder="手机号" v-decorator="['mobile', {rules: [{ required: true, pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号' }], validateTrigger: 'change'}]">
              <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>

          <a-row :gutter="16">
            <a-col class="gutter-row" :span="16">
              <a-form-item>
                <a-input size="large" type="text" placeholder="验证码" v-decorator="['captcha', {rules: [{ required: true, message: '请输入验证码' }], validateTrigger: 'blur'}]">
                  <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-button
                class="getCaptcha"
                tabindex="-1"
                :disabled="state.smsSendBtn"
                @click.stop.prevent="getCaptcha"
                v-text="!state.smsSendBtn && '获取验证码' || (state.time+' s')"
              ></a-button>
            </a-col>
          </a-row>
        </a-tab-pane>
      </a-tabs> -->

      <a-form-item>
        <a-checkbox v-decorator="['rememberMe']">自动登录</a-checkbox>
        <!-- <router-link
          :to="`/user/changePwd`"
          class="forge-password"
          style="float: right; color: #9fa2a8; font-size: 12px"
          >忘记密码</router-link
        > -->
      </a-form-item>

      <a-form-item style="margin-top: 24px">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="state.loginBtn"
          :disabled="state.loginBtn"
          >确定</a-button
        >
      </a-form-item>

      <div class="user-login-other">
        <!-- <span>其他登录方式</span>
        <a>
          <a-icon class="item-icon" type="wechat" @click="getWeChatLogin"></a-icon>
        </a>
        <a>
          <img style="width:25px; height: 22px;margin-left: 10px" src="@/assets/QQ.png" @click="getWeChatLogin"></img>
        </a> -->
        <!-- <a>
          <a-icon class="item-icon" type="weibo-circle"></a-icon>
        </a> -->
      </div>
    </a-form>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/common'
//  no-unused-vars
import md5 from 'md5'
//  no-unused-vars
import { getSmsCaptcha, imgcode, wechatLogin } from '@/api/login'
import { settingInfo } from '@/api/system/system'
export default {
  data() {
    return {
      codesrc: null,
      randomStr: null,
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type: 0 email, 1 loginText, 2 telephone
      loginType: 0,
      isLoginError: false,
      errorMsg: '',
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 loginText, 2 telephone
        loginType: 0,
        smsSendBtn: false
      }
    }
  },
  created() {
    this.getImgCode()
    // this.getSettingInfo()
  },
  mounted() {
    this.myBrowser()
  },
  activated() {
    this.form.resetFields()
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    // 判断浏览器种类函数-处理兼容性
    myBrowser() {
      var userAgent = navigator.userAgent // 取得浏览器的userAgent字符串
      var isOpera = userAgent.indexOf('Opera') > -1
      console.log(userAgent)
      if (isOpera) {
        return 'Opera'
      } // 判断是否Opera浏览器
      if (userAgent.indexOf('Firefox') > -1) {
        return 'FF'
      } // 判断是否Firefox浏览器
      if (userAgent.indexOf('Chrome') > -1) {
        return 'Chrome'
      }
      if (userAgent.indexOf('Safari') > -1) {
        return 'Safari'
      } // 判断是否Safari浏览器
      if (userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 && !isOpera) {
        this.$message.warning('请勿使用ie浏览器或ie兼容模式进行操作，建议使用极速模式')
        return 'IE'
      }
    },
    // handler
    handleLoginTextOrEmail(rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    getWeChatLogin() {
      return wechatLogin().then(res => {
        if (res.code === 0) {
          location.href = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    handleTabClick(key) {
      this.customActiveKey = key
      // this.form.resetFields()
    },
    handleSubmit(e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        customActiveKey,
        Login
      } = this

      state.loginBtn = true

      const validateFieldsKey =
        customActiveKey === 'tab1' ? ['loginText', 'password', 'captcha', 'orgCode'] : ['mobile', 'captcha']

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          console.log('values--->', values)
          const loginParams = { ...values }
          delete loginParams.loginText
          loginParams[!state.loginType ? 'email' : 'loginText'] = values.loginText
          // loginParams.password = md5(values.password)
          loginParams.randomStr = this.randomStr
          // if (this.$store.getters.sysConfig.stationStatus === 0) {
          Login(loginParams)
            .then(res => this.loginSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false
            })
          // } else {
          //   this.$message.error(this.$store.getters.sysConfig.stationCloseInfo || '系统维护中。。。')
          // }
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },

    // 获取信息
    getSettingInfo() {
      return settingInfo().then(res => {
        if (res.code === 0) {
          this.$store.commit('SET_CONFIG', res.data)
          if (res.data && res.data.sysTitle) {
            window.document.title = res.data.sysTitle
          }
          if (res.data && res.data.logoUrl && res.data.logoUrl.imagePathSmall) {
            document.getElementById('iconLogo').href = res.data.logoUrl.imagePathSmall
          }
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    getCaptcha(e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state
      } = this

      validateFields(['mobile'], { force: true }, (err, values) => {
        if (!err) {
          state.smsSendBtn = true

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)

          const hide = this.$message.loading('验证码发送中..', 0)
          getSmsCaptcha({ mobile: values.mobile })
            .then(res => {
              setTimeout(hide, 2500)
              this.$notification['success']({
                message: '提示',
                description: '验证码获取成功，您的验证码为：' + res.result.captcha,
                duration: 8
              })
            })
            .catch(err => {
              setTimeout(hide, 1)
              clearInterval(interval)
              state.time = 60
              state.smsSendBtn = false
              this.requestFailed(err)
            })
        }
      })
    },
    async getImgCode() {
      await imgcode().then(res => {
        const raw = res.data
        const { randomstr } = res.headers
        this.randomStr = randomstr
        this.codesrc = URL.createObjectURL(raw)
      })
    },
    loginSuccess(res) {
      console.log('res--->', res)
      if (res.code === 0) {
        this.$router.push({ name: '' }, () => {
          this.$notification.success({
            message: '欢迎',
            description: `${timeFix()}，欢迎回来`
          })
        })
        this.isLoginError = false
      } else {
        this.requestFailed(res)
      }
    },
    requestFailed(err) {
      console.dir(err.response)

      this.isLoginError = true
      this.getImgCode()
      this.errorMsg =
        ((err.response || {}).data || {}).msg ||
        err.msg ||
        ((err.response || {}).data || {}).message ||
        '请求出现错误，请稍后再试'
      this.$notification['error']({
        message: '错误',
        description: this.errorMsg,
        duration: 4
      })
    }
  }
}
</script>

<style lang="less" scoped>
.user-layout-login {
  background: white;
  border-radius: 8px;
  padding: 40px 80px 60px 80px;
  width: 500px;
  box-shadow: 0 6px 20px 5px rgba(40, 120, 255, 0.1), 0 16px 24px 2px rgba(0, 0, 0, 0.05);

  label {
    font-size: 14px;
  }

  .login-title {
    text-align: center;
    font-size: 18px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(26, 173, 25, 0.7);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: rgba(26, 173, 25, 1);
      }
    }

    .register {
      float: right;
    }
  }
}

@media screen and (max-height: 723px) {
  .user-layout-login {
    padding: 20px 80px 22px 80px;
  }
}
</style>
